<?php
class Silk_Mapi_AccountController extends Silk_Mapi_Controller_Action{
    const XML_PATH_EMAIL_RECIPIENT  = 'contacts/email/recipient_email';
    const XML_PATH_EMAIL_SENDER     = 'contacts/email/sender_email_identity';
    const XML_PATH_EMAIL_TEMPLATE   = 'contacts/email/email_template';
    const XML_PATH_ENABLED          = 'contacts/contacts/enabled';

    public function indexAction() {
        echo "OK";
    }

    private function _getSession() {
        return Mage::getSingleton('customer/session');
    }

    public function loginAction() {
        $username = $this->getRequest()->getParam('username');
        $password = $this->getRequest()->getParam('password');
        $mid = $this->getRequest()->getParam('mid');

        if ($username && $password && $mid) {
            $originUsername = $username;
            if(preg_match("/^[1][34578][0-9]{9}$/",$username))
            {
                $email = "{$username}@hahahui.cn";
            }
            else
            {
                //使用用户名登录首先根据firstname获取email然后登录
                $collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToFilter('firstname',array('eq'=>$username));
                $model = $collection->getFirstItem();
                $email = $model->getEmail();
            }

            $websitId = 0;
            $collection = Mage::getModel('customer/customer')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('email', array('eq'=>$email));

            if($collection->count())
            {
                $item = $collection->getFirstItem();
                $websitId = $item->getWebsiteId();
            }

            if(!$websitId)
            {
                $this->renderError('用户地区信息无法获取！');
                return;
            }

            $customer = Mage::getModel('customer/customer')->setWebsiteId($websitId);
            $customer->loadByEmail($email);
            if(!$customer->getId())
            {
                $this->renderError("用户名不存在！", 404);
                return;
            }

            if($customer->getConfirmation() && $customer->isConfirmationRequired())
            {
                $this->renderError("您的帐号正在审核中，请稍候尝试登录！", 500);
                return;
            }

            if(!$customer->validatePassword($password))
            {
                $this->renderError("帐号错误或密码错误请核对后重试！");
                return;
            }

            $token = Mage::getModel('mapi/token')->loadByCustomer($customer);
            $token->setMid($mid);

            if(!$token->getId())
            {
                $token->setCustomerId($customer->getId());
                $token->setWebsiteId($websitId);
            }
            $token->save();

            $data = array();
            $data['token'] = $token->getToken();
            $data['token_secret'] = $token->getTokenSecret();
            $data['website_id'] = $websitId;
            $data['website_code'] = Mage::getModel('core/website')->load($websitId)->getCode();

            $info = array();
            $info['name'] = $customer->getFirstname();
            $info['store_name'] = $customer->getLastname();
            $info['email'] = $customer->getEmail();
            $info['mobile'] = $customer->getMobile();

            $account = Mage::helper('rewardpoints/customer')->getAccountByCustomer($customer);
            $info['points'] = $account->getPointBalance();
            $data['info'] = $info;
            /*Mage::dispatchEvent('customer_register_success',
                array('account_controller' => $this, 'customer' => $customer)
            );*/

            $this->render($data);
        }
        else
        {
            $this->renderError("请求数据错误！", 500);
        }
    }

    public function infoAction() {
        $customer = $this->_getSession()->getCustomer();
        if(!$customer || !$customer->getId())
        {
            $this->renderError("登录出错");
            return;
        }

        $info = array();
        $info['name'] = $customer->getFirstname();
        $info['store_name'] = $customer->getLastname();
        $info['email'] = $customer->getEmail();
        $info['mobile'] = $customer->getMobile();
        $account = Mage::helper('rewardpoints/customer')->getAccountByCustomer($customer);
        $info['points'] = $account->getPointBalance();

        $this->render($info);
    }

    /*
    {"register":{"mobile":"18380478984",
    "firstname":"adger",
    "lastname":"abc",
    "password":"123456",
    "confirmation":"123456"},
    "region_id":"533",
    "city_id":"160",
    "website_id":"1464",
    "street":"chengdu",
    "shippingname":"yangjie",
    "shippingmobile":"18380478984"}
    */
    public function registerAction()
    {

        $request = $this->getRequest();
        $params = $this->getRequest()->getParam('register');
        $website = Mage::getModel('core/website')->load($request->getParam('website_id'));
        if(!$website || !$website->getId())
        {
            $this->renderError("地区不正确!");
            return;
        }

        $customer = Mage::getModel('customer/customer')->setWebsiteId($website->getId());
        $email = $params['mobile']."@hahahui.cn";
        $customer->loadByEmail($email);
        if($customer->getId())
        {
            $this->renderError("手机号已注册!");
            return;
        }

        $collection = $customer->getCollection()->addAttributeToFilter('firstname', array('eq'=>$params['firstname']));
        if($collection->count())
        {
            $this->renderError("用户名已注册!");
            return;
        }

        $customer->setEmail($email);
        $customer->setMobile($params['mobile']);
        $customer->setFirstname($params['firstname']);
        $customer->setLastname($params['lastname']);
        $customer->setPassword($params['password']);
        $customer->setWebsiteId($request->getParam('website_id'));

        try
        {
            $customer->save();

            $address = Mage::getModel('customer/address');
            $address->setCountryId('CN');
            $address->setRegionId($request->getParam('region_id'));

            $city = "";
            $cityModel = Mage::getModel("chinaarea/city")->load($request->getParam('city_id'));
            if($cityModel && $cityModel->getId())
            {
                $city .= $cityModel->getDefaultName();
            }
            $website = Mage::getModel('core/website')->load($request->getParam('website_id'));
            if($website && $website->getId())
            {
                $city .= ' '.$website->getName();
            }
            $address->setCity($city);
            $address->setFirstname($request->getParam('shippingname'));
            $address->setLastname("HHH");
            $address->setStreet($request->getParam('street'));
            $address->setTelephone($request->getParam('shippingmobile'));
            $address->setCustomer($customer);
            $address->save();

            if($address && $address->getId())
            {
                $customer->setDefaultBilling($address->getId());
                $customer->setDefaultShipping($address->getId());
                $customer->save();
            }
            Mage::dispatchEvent('customer_register_success',
                array('account_controller' => $this, 'customer' => $customer)
            );
            $this->render();
        }
        catch(Exception $e)
        {
            $this->renderError($e->getMessage());
        }
    }

    public function registerFromYiiAction()
    {
        $request = $this->getRequest();
        $params = $this->getRequest()->getParam('register');
        $website = Mage::getModel('core/website')->load($request->getParam('website_id'));
        if(!$website || !$website->getId())
        {
            $this->renderError("地区不正确!");
            return;
        }

        $customer = Mage::getModel('customer/customer')->setWebsiteId($website->getId());
        $email = $params['mobile']."@hahahui.cn";
        $customer->loadByEmail($email);
        if($customer->getId())
        {
            $this->renderError("手机号已注册!");
            return;
        }

        $collection = $customer->getCollection()->addAttributeToFilter('firstname', array('eq'=>$params['firstname']));
        if($collection->count())
        {
            $this->renderError("用户名已注册!");
            return;
        }

        $customer->setEmail($email);
        $customer->setMobile($params['mobile']);
        $customer->setFirstname($params['firstname']);
        $customer->setPassword($params['password']);
        $customer->setWebsiteId($request->getParam('website_id'));

        try
        {
            $customer->save();
            $this->render($customer->getId());
        }
        catch(Exception $e)
        {
            $this->renderError($e->getMessage());
        }
    }

    public function ordersAction() {
        $customer = $this->getCustomer();
        $collection = Mage::getModel('sales/order')->getCollection()
            ->addFieldToFilter('customer_id', array('eq'=>$customer->getId()))
            ->setOrder('entity_id','desc');
        //echo $customer->getName();
        $orders = array();
        foreach($collection as $item)
        {
            $createdAt = date("Y-m-d", Mage::getModel('core/date')->timestamp($item->getCreatedAt()));
            $orders[] = array(
                'id'=>$item->getId(),
                'increment_id'=>$item->getIncrementId(),
                'created_at'=>$createdAt,
                'status_code'=>$item->getStatus(),
                'status'=>$item->getStatusLabel(),
                'subtotal'=>$item->getSubtotal(),
                'grand_total'=>$item->getGrandTotal(),

                'payment_method' => "货到付款",
                'shipping_method' => "免费配送",
                'shipping_address' => array(
                    'name'=>$item->getBillingAddress()->getFirstname(),
                    'mobile'=>$item->getBillingAddress()->getTelephone(),
                    'address'=>$item->getBillingAddress()->format('oneline')
                ),
                'items'=>$this->getAllItemData($item)
            );
        }
        $this->render($orders);
    }

    public function orderAction()
    {
        $id = $this->getRequest()->getParam('id');
        $order = Mage::getModel('sales/order')->load($id);
        $data = array();
        $createdAt = date("Y-m-d", Mage::getModel('core/date')->timestamp($order->getCreatedAt()));
        $billingAddress = $order->getBillingAddress();
        if(!$billingAddress) $billingAddress = Mage::getModel('customer/address');
        $data = array(
                'id'=>$order->getId(),
                'increment_id'=>$order->getIncrementId(),
                'created_at'=>$createdAt,
                'status'=>$order->getStatusLabel(),
                'status_code'=>$order->getStatus(),
                'subtotal'=>$order->getSubtotal(),
                'grand_total'=>$order->getGrandTotal(),

                'payment_method' => "货到付款",
                'shipping_method' => "免费配送",
                'shipping_address' => array(
                    'name'=>$billingAddress->getFirstname(),
                    'mobile'=>$billingAddress->getTelephone(),
                    'address'=>$billingAddress->format('oneline')
                ),
                'items'=>$this->getAllItemData($order)
            );
        $this->render($data);
    }

    public function getAllItemData($order)
    {
        $_imageHelper = Mage::helper('catalog/image');
        $items = $order->getAllItems();

        $itemsData = array();

        foreach($items as $item)
        {
            $itemsData[] = array(
                'item_id'=>$item->getId(),
                'product_id'=>$item->getProductId(),
                'name'=>$item->getName(),
                'price'=>$item->getPrice(),
                'image'=>$_imageHelper->init($item->getProduct(), 'small_image')->resize(135)."",
                'qty'=>intval($item->getQtyOrdered()),
                'stock_qty'=>intval($item->getProduct()->getStockItem()->getQty())
            );
        }
        return $itemsData;
    }

    public function websitesAction() {
        $db = Mage::getSingleton('core/resource')->getConnection('core_read');
        $data = array();
        $collection = Mage::getModel('directory/region')->getCollection()->addFieldToFilter('country_id', array('eq'=>'CN'));
        foreach($collection as $region)
        {
            $province = array('value'=>$region->getId(),'text'=>$region->getName());
            $citys = array();
            $cityCollection = Mage::getModel('chinaarea/city')->getCollection()->addFieldToFilter('region_id',array('eq'=>$region->getId()));
            foreach($cityCollection as $city)
            {
                $city = array('value'=>$city->getId(), 'text'=>$city->getDefaultName());
                $areas = array();
                // $areaCollection = Mage::getModel('chinaarea/area')->getCollection()->addFieldToFilter('city_id',array('eq'=>$city['value']));
                // foreach($areaCollection as $area)
                // {
                //     $area = array('value'=>$area->getId(), 'text'=>$area->getDefaultName());
                //     $areas[] = $area;
                // }
                $sql = "select `area`.*,website.website_id from directory_country_area `area` right join core_website website on `area`.area_id=website.area_id where `area`.city_id='{$city['value']}'";
                $query = $db->query($sql);
                $areaCollection = $query->fetchAll();
                foreach($areaCollection as $website)
                {
                    $area = array('value'=>$website['website_id'], 'text'=>$website['default_name']);
                    $areas[] = $area;
                }

                $city['children'] = $areas;
                $citys[] = $city;
            }
            $province['children'] = $citys;
            $data[] = $province;
        }

        $this->render($data);
    }

    public function infoPostAction() {

    }

    public function changePasswordAction()
    {
        $oldpassword = $this->getRequest()->getParam('oldpassword');
        $password = trim($this->getRequest()->getParam('password'));
        $confirmpassword = $this->getRequest()->getParam('confirmpassword');
        $firstname = trim($this->getRequest()->getParam('firstname'));
        $lastname = trim($this->getRequest()->getParam('lastname'));
        $mobile = trim($this->getRequest()->getParam('mobile'));
        $changePassword = $this->getRequest()->getParam('changePassword');
        $customer = $this->getCustomer();

        if($password) $changePassword = 1;

        if($changePassword)
        {
            if(!$password)
            {
                $this->renderError("密码不能为空");
                return;
            }

            if($password && $password != $confirmpassword)
            {
                $this->renderError("两次输入密码不一致");
                return;
            }

            $customer->setPassword($password);
        }
        else
        {
            if(!$firstname)
            {
                $this->renderError("用户名不能为空{$changePassword}!");
                return;
            }

            if(!$lastname)
            {
                $this->renderError("店铺名不能为空!");
                return;
            }

            if(!$mobile)
            {
                $this->renderError("手机不能为空!");
                return;
            }

            $customer->setFirstname($firstname);
            $customer->setLastname($lastname);
            $customer->setMobile($mobile);
            $email = "{$mobile}@hahahui.cn";
            $customer->setEmail($email);
        }

        $customer->save();
        $this->render(array(), "修改成功!");
    }

    public function resetPasswordAction() {
        $mobile = (string) $this->getRequest()->getParam('email');
        if($mobile)
        {
            if (!preg_match("/^[1][34578][0-9]{9}$/", $mobile)) {
                $this->renderError("手机号码格式不正确.");
                return;
            }

            $email = "{$mobile}@hahahui.cn";
            $collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToFilter('email',array('eq'=>$email));
            $item = $collection->getFirstItem();

            if(!$item || !$item->getId())
            {
                $this->renderError("没有找到此用户。");
                return;
            }

            /** @var $customer Mage_Customer_Model_Customer */
            $customer = Mage::getModel('customer/customer')
                ->setWebsiteId($item->getWebsiteId())
                ->loadByEmail($email);

            try {
                $newResetPassword =  Mage::helper('core')->getRandomString(6, Mage_Core_Helper_Data::CHARS_PASSWORD_DIGITS);
                $customer->setPassword($newResetPassword);
                $customer->save();
                $sms = Mage::getSingleton('mapi/sms');
                $sms->sendText($mobile, "您的网站登录码已重置为 {$newResetPassword} 请尽快登录系统重置。");
            } catch (Exception $e) {
                $this->renderError($e->getMessage());
                return;
            }
            $this->renderError("您的密码已重置，您的手机将收到一条包含密码的短信，请在收到短信后登录系统重置密码。");
        }
        else
        {
            $this->renderError("请输入手机号码");
        }
    }

    public function passwordUpdateAction() {
        $password = $this->getRequest()->getParam('password');

        try
        {
            $customer = $this->getCustomer();
            $customer->setPassword($password);
            $customer->save();
            $this->render(array());
        }
        catch(Exception $e)
        {
            $this->renderError($e->getMessage());
        }

    }

    public function addressAction() {
        $customer = $this->getCustomer();
        $collection = Mage::getModel('customer/address')->getCollection();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('parent_id', array('eq'=>$customer->getId()));
        $address = $collection->getFirstItem();

        if($address && $address->getId())
        {
            $address = Mage::getModel('customer/address')->load($address->getId());
            $data = array();
            $data['name'] = $address->getFirstname();
            $data['mobile'] = $address->getTelephone();
            $street = $address->getStreet();
            $data['address'] = $street?$street[0]:'';
            $this->render($data);
        }
        else
        {
            $this->renderError('地址不存在！');
        }
    }

    public function addressUpdateAction() {

    }

    public function pageAction()
    {
        $code = $this->getRequest()->getParam('code');
    }

    public function contactAction()
    {
        $post = $this->getRequest()->getParams();
        if ( $post ) {
            $translate = Mage::getSingleton('core/translate');
            /* @var $translate Mage_Core_Model_Translate */
            $translate->setTranslateInline(false);
            try {
                $postObject = new Varien_Object();
                $postObject->setData($post);

                $error = false;

                if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
                    $error = true;
                }

                if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
                    $error = true;
                }

                // if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                //     $error = true;
                // }


                if ($error) {
                    throw new Exception();
                }
                $mailTemplate = Mage::getModel('core/email_template');
                /* @var $mailTemplate Mage_Core_Model_Email_Template */
                $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                    ->setReplyTo($post['email'])
                    ->sendTransactional(
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
                        null,
                        array('data' => $postObject)
                    );

                if (!$mailTemplate->getSentSuccess()) {
                    throw new Exception();
                }

                $translate->setTranslateInline(true);

                $this->render(array(),"您的意见已提交，谢谢您的反馈！");

                return;
            } catch (Exception $e) {
                $translate->setTranslateInline(true);

                $this->renderError("提交失败请稍后尝试！".$e->getMessage());
                return;
            }

        } else {
            $this->renderError("请填写数据！");
        }
    }

    public function activeoldAction()
    {
        $id = $this->getRequest()->getParam('id');

        $account = Mage::getModel('customer/customer')->load($id);
        if($account && $account->getId())
        {
            try
            {
                $account->setConfirmation(null);
                $account->save();
                //print_r($account->getData());
                $this->render(array(), '激活成功！');
            }
            catch(Exception $e)
            {
                $this->renderError($e->getMessage());
            }
        }else
        {
            $this->renderError('当前账号不存在！');
        }
    }

    //激活用户
    public function activeAction()
    {
        $id = $this->getRequest()->getParam('id');
        $websiteId = $this->getRequest()->getParam('website_id');

        //如果提供了WebsiteID 按照老的方式激活用户
        //如果有站点则按照新版激活
        if($websiteId)
        {
            $name = $this->getRequest()->getParam('name');
            $phone = $this->getRequest()->getParam('phone');
            $street = $this->getRequest()->getParam('address');

            $account = Mage::getModel('customer/customer')->load($id);
            $website = Mage::getModel('core/website')->load($websiteId);

            if($account && $account->getId() && $websiteId)
            {
                try
                {
                    $account->setConfirmation(null);
                    $account->setWebsiteId($websiteId);
                    $account->save();

                    $address = $account->getAddressesCollection()->getFirstItem();

                    //重新激活一个用户是
                    if($address && $address->getId())
                    {
                        $region = Mage::getModel('directory/region')->load($website->getProvinceId());
                        $address->setFirstname($name)
                            ->setLastname("HHH")
                            ->setStreet($street)
                            ->setCity($website->getName())
                            ->setTelephone($phone)
                            ->setCustomerId($account->getId())
                            ->setCountryId($region->getCountryId())
                            ->setRegionId($region->getId());

                        $addressErrors = $address->validate();
                        $address->save();
                    }
                    else
                    {
                        $address = Mage::getModel('customer/address');
                        $address->setId(null)
                            ->setIsDefaultBilling(1)
                            ->setIsDefaultShipping(1);

                        $region = Mage::getModel('directory/region')->load($website->getProvinceId());
                        $address->setFirstname($name)
                            ->setLastname("HHH")
                            ->setStreet($street)
                            ->setCity($website->getName())
                            ->setTelephone($phone)
                            ->setCustomerId($account->getId())
                            ->setCountryId($region->getCountryId())
                            ->setRegionId($region->getId());

                        $addressErrors = $address->validate();

                        $address->save();
                        $account->addAddress($address);

                        $account->save();

                        if($addressErrors)
                        {
                            $this->render($addressErrors, '激活出错！');
                        }
                        else
                        {
                            $this->render(array(), '激活成功！');
                        }
                    }

                    //print_r($account->getData());
                    $this->render(array(), '激活成功！');
                }
                catch(Exception $e)
                {
                    $this->renderError($e->getMessage());
                }
            }
            else
            {
                $this->renderError('当前账号不存在！');
            }
        }
        else
        {
            return $this->activeoldAction();
        }
    }

    public function syncStoreAction()
    {
        $id = $this->getRequest()->getParam('id');
        $customer = Mage::getModel('customer/customer')->load($id);
        if($customer && $customer->getId())
        {
            $websiteId = $customer->getWebsiteId();
            // if($websiteId==5 || $websiteId==7 || $websiteId==9)
            // {
            //     $this->render(array());
            //     return;
            // }
            if(!$websiteId) $websiteId = 0;
            $website = Mage::getModel('core/website')->load($websiteId);
            $address = $customer->getAddressesCollection()->getFirstItem();

            $name = $this->getRequest()->getParam('name');
            $phone = $this->getRequest()->getParam('phone');
            $street = $this->getRequest()->getParam('address');

            if($address && $address->getId())
            {
                $address->setFirstname($name)
                    ->setStreet($street)
                    ->setTelephone($phone);
                $addressErrors = $address->validate();

                $address->save();

                if($addressErrors)
                {
                    $this->render($addressErrors, '激活出错！');
                }
                else
                {
                    $this->render(array(), '激活成功！');
                }
            }
            else
            {
                $address = Mage::getModel('customer/address');
                $address->setId(null)
                    ->setIsDefaultBilling(1)
                    ->setIsDefaultShipping(1);

                $region = Mage::getModel('directory/region')->load($website->getProvinceId());
                $address->setFirstname($name)
                    ->setLastname("HHH")
                    ->setStreet($street)
                    ->setCity($website->getName())
                    ->setTelephone($phone)
                    ->setCustomerId($customer->getId())
                    ->setCountryId($region->getCountryId())
                    ->setRegionId($region->getId());

                $addressErrors = $address->validate();

                $address->save();
                $customer->addAddress($address);

                $customer->save();

                if($addressErrors)
                {
                    $this->render($addressErrors, '激活出错！');
                }
                else
                {
                    $this->render(array(), '激活成功！');
                }
            }
        }
        $this->render(array());
    }

    public function delCustomerAction($id)
    {
        $id = $this->getRequest()->getParam('id');
        $customer = Mage::getModel('customer/customer')->load($id);
        if($customer && $customer->getId())
        {
            if($customer->getConfirmation())
            {
                $orders = Mage::getModel('sales/order')->addFieldToFilter('customer_id', array('eq'=>$customer->id));
                if(!count($orders))
                {
                    $customer->delete();
                    $this->render(array());
                }
            }
        }
        $this->render(array());
    }
}